/*
 * Cookie.java
 *
 * Created on 2008-2-26, AM 11:08
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package orest.common.util;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

/**
 * This class provide the opration about cookie, for example add cookie value,
 * get cookie value and store data into tomcat's context node of server.xml.
 * This class is define for share the session data between the nast.org.cn and 
 * tech110.cn
 * 
 * @author yan dongdong
 */
public class CookieOperation extends HttpServlet {
    
    /** Creates a new instance of Cookie */
    public CookieOperation() {
    }
    
    /**
     * Date: 2008/02/26
     * Input: response  used it to add cookie infomation to client
     *        sessionid it will be write to client by cookie
     * output: true/false
     * Description: Write the session id and the path into Cookie and 
     *              return whether or not the operation successful.
     */
    public void addCookieValue(HttpServletResponse response, 
                       String sessionid) throws ServletException, IOException {
        
        try{
            Cookie ssocookie = new Cookie("SSOSESSIONID", sessionid);
            // we want the cookie to be returned to any app below root
            ssocookie.setPath("/");
            ssocookie.setMaxAge(60*60);
            // adding the cookie to the HttpResponse
            response.addCookie(ssocookie);
        }
        catch(Exception ex) {
            ex.printStackTrace();
            System.out.println("The error have occured in the class of CookieOperation" +
                                " and the function is addCookieValue");
        }
    }
    
    /**
     * Date: 2008/02/26
     * Input: request  used it to get sessionid from cookie infomation
     *        name     session key value
     * output: sessionid
     * Description: Get session id from cookie and if the user have login,
     *              will return the session id else return null.
     */
    public static String getCookieValue(HttpServletRequest request, String name) {
        boolean found = false;
        String result = null;
        Cookie[] cookies = request.getCookies();
        if (cookies!=null) {
            int i = 0;
            while (!found && i < cookies.length) {
                if (cookies[i].getName().equals(name)) {
                    found=true;
                    result = cookies[i].getValue();
                }
                i++;
            }
        }
       
        return (result);
    }


}
